package com.zs.studentmanager.controller;

import com.zs.studentmanager.common.ResponseCodeEnum;
import com.zs.studentmanager.common.Result;
import com.zs.studentmanager.entity.domain.User;
import com.zs.studentmanager.entity.vo.PageVo;
import com.zs.studentmanager.service.UserService;
import com.zs.studentmanager.utils.CommonUtils;
import com.zs.studentmanager.utils.Md5Util;
import com.zs.studentmanager.utils.UploadUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;

/**
 * @author: 周小白
 * @date: 2024-01-20 15:15
 **/
@RestController
@RequestMapping("/user")
@Tag(name= "用户管理")
public class UserController {

    @Value("${user.icon}")
    private String path;

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }



    /**
     * 分页查询
     * @param pageNum 当前页码
     * @param pageSize 每页条数
     * @return Result
     */
    @GetMapping("/list")
    @Operation(summary = "分页查询用户列表")
    public Result getUserList(@RequestParam(value = "currentPage", defaultValue = "1") Integer pageNum,
                              @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                              @RequestParam(value = "searchValue", defaultValue = "") String searchValue,
                              @RequestParam(value = "status", defaultValue = "") String status) {
        // 参数校验
        if (pageNum < 1 || pageSize < 1) {
            return Result.fail(ResponseCodeEnum.NO_PARAM);
        }

        PageVo<User> pageVo = userService.getUserPageList(pageNum, pageSize, searchValue, status);

        return Result.success(pageVo);
    }




    /**
     * 新增用户
     * @param user 用户信息
     * @return Result
     */
    @PostMapping("/add")
    @Operation(summary = "新增用户")
    @Transactional(rollbackFor = Exception.class)
    public Result addUser(@RequestBody User user) {
        // 参数校验
        if (StringUtils.isBlank(user.getUserName()) ||
                StringUtils.isBlank(user.getPassword()) ||
                user.getStatus() == null ) {
            return Result.fail(ResponseCodeEnum.NO_PARAM);
        }

        user.setCreateTime(LocalDateTime.now());
        user.setPassword(Md5Util.md5(user.getPassword()));
        long currentUserId = CommonUtils.getCurrentUserId();
        user.setCreateBy(currentUserId);

        // 新增用户
        boolean result = userService.save(user);
        if (!result) {
            return Result.fail(ResponseCodeEnum.SYSTEM_ERROR);
        }

        return Result.success();
    }




    /**
     * 查询用户详情
     * @param id  用户id
     * @return Result
     */
    @GetMapping("/{id}")
    @Operation(summary = "查询用户详情")
    public Result getUserDetails(@PathVariable("id") Long id) {
        // 参数校验
        if (id == null) {
            return Result.fail(ResponseCodeEnum.NO_PARAM);
        }

        // 查询用户
        User user = userService.getById(id);
        if (user == null) {
            return Result.fail("用户不存在");
        }

        return Result.success(user);
    }



    /**
     * 更新用户
     * @param user 用户信息
     * @return Result
     */
    @PutMapping("/update")
    @Operation(summary = "更新用户")
    @Transactional(rollbackFor = Exception.class)
    public Result updateUser(@RequestBody User user) {
        // 参数校验
        if (user.getId() == null || StringUtils.isBlank(user.getUserName()) ||
                StringUtils.isBlank(user.getPassword()) ||
                user.getStatus() == null) {
            return Result.fail(ResponseCodeEnum.NO_PARAM);
        }

        user.setUpdateTime(LocalDateTime.now());
        long currentUserId = CommonUtils.getCurrentUserId();
        user.setUpdateBy(currentUserId);

        // 更新用户
        boolean result = userService.updateById(user);
        if (!result) {
            return Result.fail(ResponseCodeEnum.SYSTEM_ERROR);
        }

        return Result.success();
    }





    /**
     * 删除用户
     * @param id 用户id
     * @return Result
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户")
    @Transactional
    public Result deleteUser(@PathVariable("id") Long id) {
        // 参数校验
        if (id == null) {
            return Result.fail(ResponseCodeEnum.NO_PARAM);
        }

        // 删除用户
        boolean result = userService.removeById(id);
        if (!result) {
            return Result.fail(ResponseCodeEnum.SYSTEM_ERROR);
        }

        return Result.success();
    }


    /**
     * 上传文件
     * @param file 文件
     * @return Result
     */
    @PostMapping("/upload")
    @Operation(summary = "上传文件")
    public Result uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail(ResponseCodeEnum.NO_PARAM);
        }

        try {
            String fileName = UploadUtil.uploadFile(file, path);

            return Result.success(fileName);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }





    /**
     * 更新用户信息
     * @param user 用户信息
     * @return Result
     */
    @PutMapping("/info")
    @Operation(summary = "更新用户信息")
    @Transactional(rollbackFor = Exception.class)
    public Result updateUserInfo(@RequestBody User user) {
        // 参数校验
        if (user.getId() == null) {
            return Result.fail(ResponseCodeEnum.NO_PARAM);
        }

        user.setUpdateTime(LocalDateTime.now());
        long currentUserId = CommonUtils.getCurrentUserId();
        user.setUpdateBy(currentUserId);

        // 更新用户
        boolean result = userService.updateById(user);
        if (!result) {
            return Result.fail(ResponseCodeEnum.SYSTEM_ERROR);
        }

        return Result.success(user);
    }
}
